<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">
      <div class="logo">WitNova</div>
        <el-menu active-text-color="#409EFF" background-color="#f2f6f8"  text-color="#000" :default-active="$route.path" 
            router>
            <el-menu-item index="/HomePage/ChatPage">
                <el-icon>
                    <Management />
                </el-icon>
                <span>智能陪练室</span>
            </el-menu-item>
            <el-menu-item index="/HomePage/DebateDashBoard">
                <el-icon>
                   <Film />
                </el-icon>
                <span>辩论仿真模拟</span>
            </el-menu-item>
            <el-sub-menu index="content">
                <template #title>
                    <el-icon>
                        <UserFilled />
                    </el-icon>
                    <span>内容工坊</span>
                </template>
                <el-menu-item >
                    <el-icon>
                        <User />
                    </el-icon>
                    <span>我的内容</span>
                </el-menu-item>
                <el-menu-item index="/Community">
                    <el-icon>
                        <Crop />
                    </el-icon>
                    <span>社区</span>
                </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="user">
                <template #title>
                    <el-icon>
                        <UserFilled />
                    </el-icon>
                    <span>我的辩论</span>
                </template>
                <el-menu-item index="/HomePage/HistoryPage">
                    <el-icon>
                        <User />
                    </el-icon>
                    <span>历史记录</span>
                </el-menu-item>
                <el-menu-item index="/HomePage/UserProfile">
                    <el-icon>
                        <Crop />
                    </el-icon>
                    <span>个人能力分析</span>
                </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="admin" >
              <template #title>
                    <el-icon>
                        <Avatar />
                    </el-icon>
                    <span>管理员</span>
              </template>
              <el-menu-item index="/HomePage/BlogVerify">
                <el-icon>
                  <List></List>
                </el-icon>
                <span>博客内容审核</span>
              </el-menu-item>
              <el-menu-item index="/HomePage/LogMonitor">
                <el-icon>
                  <BellFilled/>
                </el-icon>
                <span>日志监控</span>
              </el-menu-item>
            </el-sub-menu>
        </el-menu>
    </el-aside>
    
    <!-- 右侧主区域 -->
    <el-container class="main-container">
      <!-- 头部区域 -->
      <el-header>
          <div><strong>{{ userInfo.username }}</strong>  您好，欢迎回来</div>
          <div>今日推荐辩题：</div>
          <el-dropdown placement="bottom-end">
              <span class="el-dropdown__box">
                  <el-avatar :src="avatar" />
              </span>
              <template #dropdown>
                  <el-dropdown-menu>
                      <el-dropdown-item @click="handleCommand('profile')"  :icon="User">基本资料</el-dropdown-item>
                      <el-dropdown-item @click="handleCommand('avatar')" :icon="Crop">更换头像</el-dropdown-item>
                      <el-dropdown-item @click="handleCommand('password')" :icon="EditPen">重置密码</el-dropdown-item>
                      <el-dropdown-item @click="handleCommand('logout')" :icon="SwitchButton">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
              </template>
          </el-dropdown>
      </el-header>
      
      <!-- 中间区域 -->
      <div class="content-wrapper">
        <router-view v-slot="{ Component, route }">
          <transition>
            <component 
              :is="Component" 
              :key="route.fullPath || route.path"
            />
          </transition>
        </router-view>
      </div>
      
      <!-- 对话框组件 -->
      <el-dialog 
          style="border-radius: 30px;"
          v-model="profileDialogVisible" 
          title="账户信息"
          width="600px"
          class="custom-dialog">
          <div class="dialog-content">
          <div style="padding-bottom: 40px;">
              <span style="font-weight: 400;">用户名</span>
              <el-input style="width: 300px;padding-left: 200px;" v-model="userInfo.username" />
          </div>
          <div style="padding-bottom: 40px;">
              <span style="font-weight: 400;">个人简介</span>
              <el-input style="width: 300px;padding-left: 194px;" v-model="userInfo.introduction" />
          </div>
          <div style="padding-bottom: 40px;">
              <span style="font-weight: 400;">邮箱</span>
              <el-input style="width: 300px;padding-left: 210px;" v-model="userInfo.email" />
          </div>
          <div class="action-buttons">
              <el-button type="primary" @click="saveProfile()">保存修改</el-button>
          </div>
          </div>
      </el-dialog>
       <!-- 更换头像对话框 -->
      <el-dialog
          style="border-radius: 30px;"
          v-model="avatarDialogVisible"
          title="更换头像"
          width="500px">
          <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange">
          <img v-if="newAvatar" :src="newAvatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <el-button style="text-align: center;margin-top: 20px;" type="primary" @click="uploadAvatar">确认更换</el-button>
      </el-dialog>

      <!-- 重置密码对话框 -->
      <el-dialog
          style="border-radius: 30px;"
          v-model="passwordDialogVisible"
          title="重置密码"
          width="600px">
          <div class="password-form">
          <el-form :model="passwordForm" label-width="100px">
              <el-form-item label="旧密码">
              <el-input v-model="passwordForm.oldPassword" show-password />
              </el-form-item>
              <el-form-item label="新密码">
              <el-input v-model="passwordForm.newPassword" show-password />
              </el-form-item>
              <el-form-item label="确认密码">
              <el-input v-model="passwordForm.confirmPassword" show-password />
              </el-form-item>
          </el-form>
          <div class="dialog-actions">
              <el-button type="primary" @click="submitPassword">确认重置</el-button>
          </div>
          </div>
      </el-dialog>
      
      <!-- 底部区域 -->
      <el-footer>WitNova ©2025</el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
import { watch, ref, onMounted } from 'vue'
import { useAppStore } from "../stores/app";
import { success,error} from "../tools/messageBox"
import { useRoute } from 'vue-router'; // 从 vue-router 导入
import {getUser,changeUserInfo,changeUserAvatar,resetPassword } from "../services/userServ"
import router from '../router'
// 图标引入axios
import {
  UserFilled,
  Management,
  Film,
  User,
  Crop,
  EditPen,
  SwitchButton,
  Avatar,
  List,
  BellFilled
} from '@element-plus/icons-vue'
import { dateEquals } from 'element-plus';
const appStore= useAppStore()
const userInfo=ref(appStore.$state.userInfo)
const route = useRoute();

// 在 setup 中添加
watch(
  () => route.fullPath,
  (newPath) => {
    console.log('路由变化:', {
      path: newPath,
      matched: route.matched,
      component: route.matched[route.matched.length - 1]?.components?.default
    })
  },
  { immediate: true }
)

onMounted(async () => {
  try {
    const response = await getUser()
    console.log(response)
    userInfo.value=response
    console.log(userInfo.value)
  } catch (err) {
    const status = err?.response?.status || err?.status
    if (status === 403) {
      error('登录已过期，请重新登录')
      router.push('/Login')
    } else {
      error('请求失败')
    }
  } 
})
const avatar=userInfo.avatar

const profileDialogVisible = ref(false)
const avatarDialogVisible = ref(false)
const passwordDialogVisible = ref(false)

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
// 头像上传
const newAvatar = ref(null)

const handleCommand = (command) => {
  switch(command) {
    case 'profile':
      profileDialogVisible.value = true
      break
    case 'avatar':
      avatarDialogVisible.value = true
      break
    case 'password':
      passwordDialogVisible.value = true
      break
    case 'logout':
      appStore.logout()
      document.cookie = "authToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
      router.push('/Login')

      break
  }
}
const saveProfile = () => {
  // 保存资料逻辑
  const res= changeUserInfo(userInfo.id,userInfo.username,userInfo.phone,userInfo.email)
  if(res.code==200){
    success('资料修改成功')
    profileDialogVisible.value = false
  }else{
    error('资料修改失败，请重试')
  }
}

const handleAvatarChange = (file) => {
  // 处理头像上传预览
  const reader = new FileReader()
  reader.onload = (e) => {
    newAvatar.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const uploadAvatar = () => {
  const res= changeUserAvatar(userInfo.id,newAvatar.value)
  if(res.code==200){
    success('头像更换成功')
    avatarDialogVisible.value = false
  }else{
    error('头像更换失败，请重试')
  }
}

const submitPassword = async () => {
  const res = await resetPassword(passwordForm.value.oldPassword, passwordForm.value.newPassword)
  console.log(res)
  if (res.message == '密码修改成功') {
    success(res.message)
    passwordDialogVisible.value = false
  } else {
    error('密码重置失败，请重试')
  }
}
</script>

<style lang="scss" scoped>
.logo {
  font-size: 30px;
  font-weight: bold;
  color: #071a2d;
}


.layout-container {
    height: 100vh;
    overflow: hidden;
    .main-container {
    flex: 1; // 确保主容器占据剩余空间
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
    .el-aside {
        // background-color: #cadbff;
        background-color: #f2f6f8;
        height: 100vh;
        &__logo {
            height: 120px;
            background: url('@/assets/logo.png') no-repeat center / 120px auto;
        }
 
        .el-menu {
            border-right: none;
        }
    }
 
    .el-header {
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
 
        .el-dropdown__box {
            display: flex;
            align-items: center;
 
            .el-icon {
                color: #999;
                margin-left: 10px;
            }
 
            &:active,
            &:focus {
                outline: none;
            }
        }
    }
 
    .el-footer {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #666;
    }
}

.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow: auto; // 改为auto而非hidden以允许内容滚动
    padding: 20px; // 添加内边距使内容不贴边
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 对话框样式 */
.custom-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #e4e7ed;
  }
  .dialog-content {
    padding: 20px;
    .form-item {
      margin-bottom: 24px;
      display: flex;
    }
  }
}
.avatar-uploader {
  display: flex;
  justify-content: center;
  
  .avatar {
    width: 200px;
    height: 200px;
    border-radius: 50%;
  }
  
  :deep(.el-upload) {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
  }
}

.password-form {
  padding: 20px;
  
  .dialog-actions {
    margin-top: 24px;
    text-align: center;
  }
}

.action-buttons {
  margin-top: 32px;
  text-align: center;
}
</style>